package com.ruoyi.marketing.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.marketing.domain.MarketingAward;
import com.ruoyi.marketing.service.IMarketingAwardService;
import org.springframework.beans.BeanUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * @author Shuang_Ls
 */
public class PrizeUtils {

    public static MarketingAward gift(String marketId) {
        // 获取奖品信息列表
        List<MarketingAward> prizeList = SpringUtils.getBean(IMarketingAwardService.class).
                list(new LambdaQueryWrapper<MarketingAward>().eq(MarketingAward::getActivityId, marketId));
        // 奖品列表中的概率为累加概率
        // 需要按照添加进列表的顺序进行累加，为了数据处理方便中奖几率*100
        double sum = 0;
        List<MarketingAward> newList = new ArrayList<>();
        for (int i = 0; i < prizeList.size(); i++) {
            MarketingAward MarketingAward = prizeList.get(i);
            MarketingAward newMarketingAward = new MarketingAward();
            BeanUtils.copyProperties(MarketingAward, newMarketingAward);
            sum = sum + (Double.parseDouble(MarketingAward.getProbability()+"") * 100);
            newMarketingAward.setProbability(sum);
            newList.add(newMarketingAward);
        }

        // 生成一个随机数
        Random random = new Random();
        Collections.shuffle(prizeList);
        Double userSelect = random.nextDouble() * 2;
        for (MarketingAward prize : prizeList) {
            // 随机数小于中奖几率，则中奖
            double ratio = Double.parseDouble(prize.getProbability() + "");
            if (userSelect < ratio) {
                    return prize;
            }
        }
        return null;
    }
}
